let app = require('express')()
let fs = require('fs')
let path = require('path')
let bodyParser = require('body-parser')
let { mockPort } = require('../package.json').config

// 允许跨域
app.use(function (req, res, next) {
  let origin = req.header('origin')

  // 允许跨域
  res.header('Access-Control-Allow-Origin', origin)
  // 允许携带票据
  res.header('Access-Control-Allow-Credentials', true)

  // 允许跨域自定义的 Header
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  next()
})

// config body parser
//
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json({
  type: function (req) {
    return /json/.test(req.headers['content-type']) || /json/.test(req.headers['content-language'])
  }
}))

app.get('/', function (req, res) {
  res.send('mock server started')
})

// load routers
fs.readdirSync(path.resolve('./routers/')).forEach(function (file) {
  if (/\.js$/.test(file)) require(path.resolve('./routers/' + file))(app)
})

// 404 handler
// custom 404 page
app.use(function (req, res) {
  res.status(404).send('404')
})
// 500 handler
// custom 500 page
app.use(function (err, req, res) {
  res.status(err.status || 500).send(err)
})

// start
//
app.listen(mockPort)
